import React, { Component } from 'react';
import PropType from 'prop-types'
class Slide extends Component {
	// 6.	滑块组件设计并暴露出合理的props 

	// 7.	对滑块的props做类型校验
	static propTypes = {
		direct: PropType.string,
		// 10.	props要求传入数组控制两个滑块的颜色
		colors: PropType.array
	}
	// 8.	对滑块的props设定满足要求的默认值
	static defaultProps = {
		// 9.	props要求能够通过参数控制滑块的方向 （上下或者左右） 
		direct: 'vertical',
		colors: ['green', 'skyblue']
	}
	state = {
		pos: [0, 100],
		active: 1,
		middY: 0,
		isDrag: false,
		currDragEl: null,
	}
	handleMouseDown = (e, active) => {
		this.setState({
			middY: e.nativeEvent.offsetY,
			isDrag: true,
			currDragEl: e.target,
			active
		})
	}
	handleMouseMove = e => {
		const { middY, isDrag, currDragEl, active } = this.state
		if (isDrag) {
			const dis = this.props.direct === 'horizontal' ? e.pageX - middY - this.container.offsetLeft + this.container.offsetHeight / 2 : e.pageY - middY - this.container.offsetTop
			if (dis < 0) return
			if (dis > 100) return

			if (active === 1) {
				this.setState(({ pos }) => ({
					pos: [dis, pos[1]],
					active: dis > pos[1] ? 2 : 1
				}))
			} else {
				this.setState(({ pos }) => ({
					pos: [pos[0], dis],
					active: dis < pos[0] ? 1 : 2
				}))
			}

		}
	}

	handleMouseUp = e => {
		this.setState({
			middY: 0,
			isDrag: false,
			currDragEl: null
		})
	}
	componentDidMount() {
		console.log(this.container.offsetLeft);
		document.addEventListener('mousemove', this.handleMouseMove)
		document.addEventListener('mouseup', this.handleMouseUp)
	}
	componentWillUnmount() {
		document.removeEventListener('mousemove', this.handleMouseMove)
		document.removeEventListener('mouseup', this.handleMouseUp)
	}
	render() {
		const [top1, top2] = this.state.pos
		const { direct, colors: [color1, color2] } = this.props
		return (
			<>
				<div className={direct === 'horizontal' ? "slide horizontal" : "slide"} ref={ref => this.container = ref}>
					<div className="left" style={{ top: top1, backgroundColor: color1 }} onMouseDown={e => this.handleMouseDown(e, 1)}>
						<div className="text">{top1}</div>
					</div>
					<div className="right" style={{ top: top2, backgroundColor: color2 }} onMouseDown={e => this.handleMouseDown(e, 2)}>
						<div className="text">{top2}</div>
					</div>
				</div>
			</>


		);
	}
}

export default Slide;
